package com.iotproject.forumservice.controller.admin;

import com.iotproject.commonutils.R;
import com.iotproject.forumservice.entity.ForumComment;
import com.iotproject.forumservice.entity.vo.admin.CommentQuery;
import com.iotproject.forumservice.service.ForumCommentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("admin/forumservice/comment/")
public class AdminForumCommentController {

    @Autowired
    ForumCommentService commentService;

    @PostMapping("pageCommentCondition/{current}/{limit}")
    public R pageCommentCondition(@PathVariable("current") long current,
                                   @PathVariable("limit") long limit,
                                   @RequestBody(required = false) CommentQuery commentQuery) {
        Page<ForumComment> commentPage = new Page<>(current, limit);
        QueryWrapper<ForumComment> commentQueryWrapper = new QueryWrapper<>();

        String questionId = commentQuery.getQuestionId();
        String creatorId = commentQuery.getCreatorId();
        String recipientId = commentQuery.getRecipientId();
        String description = commentQuery.getDescription();
        String begin = commentQuery.getBegin();
        String end = commentQuery.getEnd();
        if (!StringUtils.isEmpty(description)) {
            commentQueryWrapper.like("description", description);
        }
        if (!StringUtils.isEmpty(questionId)) {
            commentQueryWrapper.eq("question_id", questionId);
        }
        if (!StringUtils.isEmpty(creatorId)) {
            commentQueryWrapper.eq("creator_id", creatorId);
        }
        if (!StringUtils.isEmpty(recipientId)) {
            commentQueryWrapper.eq("recipient_id", recipientId);
        }
        if (!StringUtils.isEmpty(begin)) {
            commentQueryWrapper.ge("gmt_modified", begin);
        }
        if (!StringUtils.isEmpty(end)) {
            commentQueryWrapper.le("gmt_modified", end);
        }
        commentQueryWrapper.orderByDesc("gmt_modified");
        commentService.page(commentPage, commentQueryWrapper);
        long total = commentPage.getTotal();
        List<ForumComment> records = commentPage.getRecords();
        return R.ok().data("total", total).data("rows", records);
    }

    @DeleteMapping("deleteCommentById/{id}")
    public R deleteCommentById(@PathVariable("id") String id) {
        boolean removeById = commentService.removeById(id);
        if (removeById) {
            return R.ok();
        }
        return R.error();
    }

}
